
#include "carousel_image_window.h"
#include "deal_http_post_details.h"
#include <QHBoxLayout>
#include <QPainter>
#include <QDebug>
#include <QButtonGroup>
#include <QJsonObject>
#include <QJsonArray>
#include <QDir>
#include <QMessageBox>
#include <iostream>
#include <QDesktopServices>

CarouselImageWindow::CarouselImageWindow(QWidget *parent)
        : QWidget(parent)
        , current_index_(0)
{
    // 添加ImageOpacity属性;
    this->setProperty("ImageOpacity", 1.0);
    // 动画切换类;
    opacity_animation_ = new QPropertyAnimation(this, "ImageOpacity");
    // 这里要设置的动画时间小于图片切换时间;
    opacity_animation_->setDuration(1500);
    network_manager_ = new QNetworkAccessManager(this);

    // 设置ImageOpacity属性值的变化范围;
    opacity_animation_->setStartValue(1.0);
    opacity_animation_->setEndValue(0.0);
    // 透明度变化及时更新绘图;
    connect(opacity_animation_, SIGNAL(valueChanged(const QVariant&)), this, SLOT(update()));
    // 设置图片切换时钟槽函数;
    connect(&image_change_timer_, SIGNAL(timeout()), this, SLOT(onImageChangeTimeout()));

    connect(network_manager_, &QNetworkAccessManager::finished, this, &CarouselImageWindow::replyFinished);
    connect(&DealHttpPostDetails::instance(), &DealHttpPostDetails::signalAdvertisement, this, &CarouselImageWindow::dealAdvertisementBack);
}

CarouselImageWindow::~CarouselImageWindow()
{

}

void CarouselImageWindow::initChangeImageButton()
{
    // 注意图片过多按钮可能放置不下;
    QButtonGroup* changeButtonGroup = new QButtonGroup;
    QHBoxLayout* hLayout = new QHBoxLayout();
    hLayout->addStretch();
    for (int i = 0; i < image_file_name_list_.count(); i++)
    {
        QPushButton* pButton = new QPushButton;
        pButton->setFixedSize(QSize(8, 8));
        pButton->setCheckable(true);
        pButton->setObjectName("Shuffling");
        pButton->installEventFilter(this);
        changeButtonGroup->addButton(pButton, i);
        button_list_.append(pButton);
        hLayout->addWidget(pButton);
    }
    hLayout->addStretch();
    hLayout->setSpacing(10);
    hLayout->setMargin(0);

    connect(changeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(onImageSwitchButtonClicked(int)));

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addStretch();
    mainLayout->addLayout(hLayout);
    mainLayout->setContentsMargins(0, 0, 0, 20);
}

void CarouselImageWindow::setImageList(QStringList imageFileNameList)
{
    image_file_name_list_ = imageFileNameList;
}

void CarouselImageWindow::addImage(QString imageFileName)
{
    image_file_name_list_.append(imageFileName);
}

void CarouselImageWindow::startPlay()
{
    // 添加完图片之后，根据图片多少设置图片切换按钮;
    initChangeImageButton();
    if (image_file_name_list_.count() == 1)
    {
        button_list_[current_index_]->setChecked(true);
    }
    else if (image_file_name_list_.count() > 1)
    {
        button_list_[current_index_]->setChecked(true);
        current_pixmap_ = QPixmap(image_file_name_list_.at(current_index_)).scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        image_change_timer_.start(2000);
        update();
    }
}

void CarouselImageWindow::onImageChangeTimeout()
{
    // 设置前后的图片;
    current_pixmap_ = QPixmap(image_file_name_list_.at(current_index_)).scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    current_index_++;
    if (current_index_ >= image_file_name_list_.count())
    {
        current_index_ = 0;
    }
    next_pixmap_ = QPixmap(image_file_name_list_.at(current_index_)).scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    button_list_[current_index_]->setChecked(true);
    // 动画类重新开始;
    opacity_animation_->start();
}

void CarouselImageWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QRect imageRect = this->rect();

    // 如果图片列表为空，显示默认图片;
    if (image_file_name_list_.isEmpty())
    {
        QPixmap backPixmap = QPixmap(":/Resources/CarouselImageBack.png").scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(imageRect, backPixmap.scaled(imageRect.size()));
    }
        // 如果只有一张图片;
    else if (image_file_name_list_.count() == 1)
    {
        QPixmap backPixmap = QPixmap(image_file_name_list_.first()).scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(imageRect, backPixmap.scaled(imageRect.size()));
    }
        // 多张图片;
    else if (image_file_name_list_.count() > 1)
    {
        float imageOpacity = this->property("ImageOpacity").toFloat();
        painter.setOpacity(1);
        painter.drawPixmap(imageRect, next_pixmap_.scaled(imageRect.size(),Qt::KeepAspectRatio, Qt::SmoothTransformation));
        painter.setOpacity(imageOpacity);
        painter.drawPixmap(imageRect, current_pixmap_.scaled(imageRect.size(),Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
}

void CarouselImageWindow::onImageSwitchButtonClicked(int buttonId)
{
    current_index_ = buttonId - 1;
    if (current_index_ == -1)
    {
        current_index_ = image_file_name_list_.count() - 1;
    }

    onImageChangeTimeout();
    image_change_timer_.start(2000);
    update();
}

void CarouselImageWindow::mousePressEvent(QMouseEvent* event)
{
    // 这里可以对当前图片进行点击然后触发每个图片对应的效果;
    // 比如web上好多类似的弹出对应的广告页面等功能;
    QDesktopServices::openUrl(QUrl(url_list_[current_index_]));
    return __super::mousePressEvent(event);
}

void CarouselImageWindow::dealAdvertisementBack(const QJsonObject &obj)
{
    if(obj.contains("results"))
    {
        QJsonArray advertisementArray = obj["results"].toArray();
        for(const auto advertisement:advertisementArray)
        {
            QJsonObject adSubObj = advertisement.toObject();
            if(adSubObj.contains("image"))
            {
                QString str = adSubObj["image"].toObject()["images"].toString();
                QString picName = QUrl(str.split("/").last()).toString();
                if(names_.contains(picName))
                {

                }
                else
                {
                    image_list_.append(str);
                }
                pic_names_.append(picName);
            }
            else
            {
                image_list_.append("");
            }
            if(adSubObj.contains("url"))
            {
                url_list_.append(adSubObj["url"].toString());
            }
            else
            {
                url_list_.append("");
            }
        }
    }

    for(const auto &url:image_list_)
    {
        if(!url.isEmpty())
        {
            QNetworkRequest request;
            request.setUrl(QUrl(url));
            network_manager_->get(request);
        }
    }
    for(const auto & pic : pic_names_)
    {
        std::cout << pic.toStdString() <<std::endl;
        addImage("./image/"+pic);
    }
    startPlay();
}

void CarouselImageWindow::replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray data = reply->readAll();
        QString uStr = reply->url().toString();
        auto *curPic =new QPixmap();
        curPic->loadFromData(data);
        curPic->save("./image/"+uStr.split("/").last());
        delete curPic;
    }
    reply->deleteLater();
}

void CarouselImageWindow::getFileName()
{
    //--1 判断文件夹是否存在
    QDir dir("./image");
    if(!dir.exists())
    {
        QMessageBox::critical(this,"error","no folder!");
        return;
    }
    names_ = dir.entryList(QDir::Files);
}

bool CarouselImageWindow::eventFilter(QObject* obj, QEvent* event)
{
    for(const auto & button : button_list_)
    {
        if (obj == button) {
            if (event->type() == QEvent::Enter)
            {
                setCursor(Qt::PointingHandCursor);
            }
            else if (event->type() == QEvent::Leave)
            {
                setCursor(Qt::ArrowCursor);
            }
        }
    }
    return __super::eventFilter(obj, event);
}